<template>
  <div class="vehicle-query-container">
    <div class="header-section">
      <el-button text size="small" @click="goBack" class="back-button">
        <el-icon><ArrowLeft /></el-icon> 返回
      </el-button>
      <h3 class="page-title">车辆信息查询</h3>
    </div>

    <!-- 查询表单 -->
    <div class="query-form-section">
      <el-form :inline="true" :model="queryForm" size="small" class="search-form">
        <el-form-item label="车牌">
          <el-input v-model="queryForm.licensePlate" placeholder="车牌" clearable style="width:100px"/>
        </el-form-item>
        <el-form-item label="品牌">
          <el-input v-model="queryForm.brand" placeholder="品牌" clearable style="width:100px"/>
        </el-form-item>
        <el-form-item label="类型">
          <el-select v-model="queryForm.typeId" placeholder="类型" clearable style="width:100px">
            <el-option label="全部" :value="null"/>
            <el-option label="轿车" :value="1"/>
            <el-option label="SUV" :value="2"/>
            <el-option label="跑车" :value="3"/>
          </el-select>
        </el-form-item>
        <el-form-item label="型号">
          <el-input v-model="queryForm.model" placeholder="型号" clearable style="width:100px"/>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" size="small" @click="handleSearch">
            <el-icon><Search /></el-icon> 查询
          </el-button>
          <el-button size="small" @click="handleReset">
            <el-icon><Refresh /></el-icon> 重置
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 数据表格 -->
    <div class="table-section">
      <el-table
          :data="tableData"
          v-loading="loading"
          size="small"
          style="width:100%"
          class="vehicle-table"
          border
          height="calc(100vh - 230px)"
          :fit="false">
        <el-table-column prop="id" label="ID" width="40" align="center" header-align="center"/>
        <!-- 优化后的图片列 -->
        <el-table-column label="图片" width="100" align="center" header-align="center">
          <template #default="{row}">
            <div class="image-container">
              <el-image
                  :src="getImageUrl(row.images)"
                  :alt="`${row.brand}${row.model}`"
                  style="width: 80px; height: 60px; object-fit: cover;"
                  :fallback-src="defaultImage"
                  preview-teleported
                  :preview-src-list="[getImageUrl(row.images)]"
                  @error="handleImageError(row)"
              ></el-image>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="licensePlate" label="车牌号" width="80" align="center" header-align="center" show-overflow-tooltip/>
        <el-table-column prop="brand" label="品牌" width="80" align="center" header-align="center" show-overflow-tooltip/>
        <el-table-column prop="model" label="型号" width="80" align="center" header-align="center" show-overflow-tooltip/>
        <el-table-column prop="typeId" label="类型" width="60" align="center" header-align="center">
          <template #default="{row}">
            {{ getTypeText(row.typeId) }}
          </template>
        </el-table-column>
        <el-table-column prop="color" label="颜色" width="60" align="center" header-align="center" show-overflow-tooltip/>
        <el-table-column prop="status" label="状态" width="60" align="center" header-align="center">
          <template #default="{row}">
            <el-tag
                :type="getStatusType(row.status).type"
                size="small"
                effect="plain">
              {{ getStatusType(row.status).text }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120" align="center" header-align="center" class="operation-column">
          <template #default="{row}">
            <el-button size="small" type="primary" @click="handleEdit(row)">
              <el-icon><Edit /></el-icon> 编辑
            </el-button>
            <el-button size="small" type="danger" @click="handleDelete(row)">
              <el-icon><Delete /></el-icon> 删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页控件 -->
    <div class="pagination-section">
      <el-pagination
          v-model:current-page="pageInfo.currentPage"
          v-model:page-size="pageInfo.pageSize"
          :total="pageInfo.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          background
          @current-change="handlePageChange"
          @size-change="handleSizeChange"
      />
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { ArrowLeft, Search, Refresh, Edit, Delete } from '@element-plus/icons-vue'
import { carList, deleteCar } from '@/api/car'
import defaultCarImage from '@/assets/default-car.jpg';
import { useMerchantInfoStore } from '@/stores/merchantInfo'

const merchantStore = useMerchantInfoStore()
const router = useRouter()
const defaultImage = defaultCarImage;


// 数据状态
const tableData = ref([])
const loading = ref(false)

const pageInfo = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

const queryForm = reactive({
  licensePlate: '',
  brand: '',
  typeId: null,
  model: ''
})

// 生成图片URL（统一处理路径逻辑）
const getImageUrl = (filename) => {
  if (!filename) return defaultImage; // 空值直接返回默认图
  return `/api/file/download.do?filename=${filename}`; // 接口路径根据实际情况调整
};

// 图片加载错误处理
const handleImageError = (row) => {
  console.error(`图片加载失败：${row.images}`);
  ElMessage.warning(`车辆【${row.licensePlate}】图片加载失败`);
};

// 获取车辆列表
const fetchCarList = async () => {
  try {
    loading.value = true
    const params = {
      pageNum: pageInfo.currentPage,
      pageSize: pageInfo.pageSize,
      merchantId: merchantStore.merchantInfo?.id,
      ...queryForm
    }

    // Object.keys(params).forEach(key => {
    //   if(params[key] === '' || params[key] === null) delete params[key]
    // })

    console.log('请求参数:', params)
    const res = await carList(params)
    console.log('响应数据:', res.data)

    if(res?.code === 200) {
      tableData.value = res.data?.records || []
      pageInfo.total = res.data?.count || 0
      // pageInfo.currentPage = res.data
      // 关键修复：从响应中提取正确的页码
      pageInfo.currentPage = res.data?.current || pageInfo.currentPage

      if(res.data?.hasNext === false && pageInfo.currentPage > 1) {
        ElMessage.warning('已经是最后一页数据')
      }
    } else {
      ElMessage.error(res?.message || '获取数据失败')
    }
  } catch(error) {
    console.error('获取车辆列表错误:', error)
    ElMessage.error('获取车辆列表失败')
  } finally {
    loading.value = false
  }
}

// 查询
const handleSearch = () => {
  pageInfo.currentPage = 1
  fetchCarList()
}

// 重置
const handleReset = () => {
  Object.keys(queryForm).forEach(key => {
    queryForm[key] = ''
  })
  queryForm.typeId = null
  handleSearch()
}

// 分页事件
const handlePageChange = (page) => {
  pageInfo.currentPage = page
  fetchCarList()
}

const handleSizeChange = (size) => {
  pageInfo.pageSize = size
  pageInfo.currentPage = 1
  fetchCarList()
}

// 编辑
const handleEdit = (row) => {
  console.log('编辑按钮点击，ID:', row.id); // 检查ID是否存在

  if (!row.id) {
    ElMessage.error('缺少车辆ID');
    return;
  }

  router.push(`/merchant/vehicle-edit/${row.id}`)
      .catch(error => {
        console.error('路由跳转失败:', error);
        ElMessage.error('跳转失败，请稍后重试');
      });
}

// 删除
const handleDelete = async (row) => {
  try {
    const params = {"id":row.id};


    await ElMessageBox.confirm(
        `确定删除车牌 ${row.licensePlate} 的车辆吗？`,
        '警告',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
    );
    console.log(params)
    const deleteRes = await deleteCar(params);
    if (deleteRes?.code === 200) {
      ElMessage.success('删除成功');
      fetchCarList();
    } else {
      ElMessage.error(deleteRes?.message || '删除失败，请重试');
    }
  } catch (error) {
    if (error === 'cancel') {
      ElMessage.info('已取消删除');
    } else {
      console.error('删除失败：', error);
      ElMessage.error('删除失败，网络或服务器异常');
    }
  }
};

// 状态标签转换
const getStatusType = (status) => {
  const statusTextMap = {0: '可租', 1: '已租', 2: '维修'}
  const statusTypeMap = {0: 'success', 1: 'warning', 2: 'info'}
  return {
    text: statusTextMap[status] || '未知',
    type: statusTypeMap[status] || 'default'
  }
}

// 车辆类型转换
const getTypeText = (typeId) => {
  const typeMap = {1: '轿车', 2: 'SUV', 3: '跑车'}
  return typeMap[typeId] || '未知'
}

// 返回
const goBack = () => {
  router.back()
}

// 初始化加载
onMounted(() => {
  fetchCarList()
})
</script>

<style scoped>
/* 容器样式 */
.vehicle-query-container {
  padding: 16px;
  height: 100vh;
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
}

/* 头部样式 */
.header-section {
  display: flex;
  align-items: center;
  margin-bottom: 16px;
}

.back-button {
  padding: 0;
  margin-right: 12px;
  font-size: 13px;
}

.page-title {
  margin: 0;
  font-size: 16px;
  font-weight: 500;
}

/* 查询表单样式 */
.query-form-section {
  margin-bottom: 16px;
  background-color: #f5f7fa;
  padding: 12px;
  border-radius: 4px;
}

.search-form :deep(.el-form-item) {
  margin-bottom: 0;
  margin-right: 12px;
}

.search-form :deep(.el-form-item__label) {
  font-size: 12px;
  padding-right: 6px;
}

/* 表格样式 */
.table-section {
  flex: 1;
  overflow: auto;
  border-radius: 4px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
  padding-right: 1px;
}

.vehicle-table {
  font-size: 12px;
  border-right: none !important;
}

.vehicle-table :deep(.el-table__header-wrapper) {
  table-layout: fixed;
}

.vehicle-table :deep(.el-table__cell) {
  padding: 4px 0;
  white-space: nowrap;
  overflow: hidden;
}

.vehicle-table :deep(.el-table th.el-table__cell) {
  background-color: #f5f7fa;
  padding: 6px 0;
  font-weight: 500;
  font-size: 12px;
}

/* 图片容器样式 */
.image-container {
  width: 80px;
  height: 60px;
  margin: 0 auto;
  border: 1px solid #f0f0f0;
  border-radius: 4px;
  overflow: hidden;
  cursor: pointer; /* 提示可点击预览 */
}

/* 颜色显示调整 */
.color-display {
  width: 16px;
  height: 16px;
  margin: 0 auto;
  border: 1px solid #ddd;
  border-radius: 50%;
  display: inline-block;
}

.price-tag {
  color: #f56c6c;
  font-weight: 500;
}

/* 分页样式 */
.pagination-section {
  margin-top: 16px;
  display: flex;
  justify-content: flex-end;
}

/* 按钮与标签样式 */
:deep(.el-button) {
  padding: 4px 8px;
  font-size: 12px;
}

:deep(.el-table-column:last-child .el-button) {
  margin-right: 4px;
  padding: 2px 6px;
}

:deep(.el-tag) {
  font-size: 11px;
  padding: 0 4px;
}

/* 图片预览弹窗优化 */
:deep(.el-image-viewer__wrapper) {
  background-color: rgba(0, 0, 0, 0.8);
}

:deep(.el-table) {
  width: 100% !important;
}

:deep(.el-table__header),
:deep(.el-table__body) {
  width: 100% !important;
}
</style>